package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.view.View;

import com.google.gson.Gson;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.RefundActivityBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.ListBean;
import com.sgb.capital.model.RefundDetailBean;
import com.sgb.capital.utils.Timer2Utils;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.InvoicePop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.adapter.BalanceDetailsAdapter;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.CostQueryModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

/**
 * 作者:张磊
 * 日期:2022/1/17 0017
 * 说明:退款单
 */
public class RefundActivity extends BaseActivity {

    private RefundActivityBinding mBinding;
    private CostQueryModel mModel;
    private BalanceDetailsAdapter mAdapter;
    private ArrayList<Bean> mBeans;
    private boolean mSel = true;
    private InvoicePop mInvoicePop;
    private TipPop mTipPop;
    private List<ListBean> mBeanList;
    private Timer2Utils mTimerUtils;
    private RefundDetailBean mData;
    private List<String> mStringList;

    public static void start(Context context, String data) {
        Intent intent = new Intent(context, RefundActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("data", data);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mBinding = DataBindingUtil.setContentView(this, R.layout.refund_activity);
        mModel = new ViewModelProvider(this).get(CostQueryModel.class);
        mBinding.rv.setLayoutManager(new GridLayoutManager(Utils.getContext(), 1));
        mAdapter = new BalanceDetailsAdapter(null);
        mBinding.rv.setAdapter(mAdapter);
        mInvoicePop = new InvoicePop(this);
        mTipPop = new TipPop(this);
        mTipPop.setOutSideDismiss(false);

    }

    public void initData() {
        mData = new Gson().fromJson(getIntent().getStringExtra("data"), RefundDetailBean.class);
        mBeans = new ArrayList<>();
        mBeans.add(new Bean("业务类型", mData.oriTradeType));
        mBeans.add(new Bean("退费单号", mData.orderId));
        mBeans.add(new Bean("原订单号", mData.oriOrderId));
        mBeans.add(new Bean("原交易流水号", mData.oriMerTrace));
        mBeans.add(new Bean("原交易金额", "￥" + Utils.getDecimalFormat(mData.oriAmount / 100.00)));
        mBeans.add(new Bean("退款金额", "￥" + Utils.getDecimalFormat(mData.amount / 100.00)));
        mBeans.add(new Bean("申请商户", mData.applyName));
        mBeans.add(new Bean("申请时间", Utils.getTime(mData.applyTime)));
        mBeans.add(new Bean("操作人", mData.handleName));
        mBeans.add(new Bean("处理时间", mData.handleTime == 0 ? "/" : Utils.getTime(mData.handleTime)));
        mAdapter.setNewInstance(mBeans);
        mModel.list(this, "2");
    }

    public void initListener() {
        mTipPop.mTvCancel.setOnClickListener(v -> {
            mTipPop.dismiss();

            if (mTipPop.mTip.contains("暂无退款验证人")) {

            } else {
                if (mTipPop.mTip.contains("发生变化") || mTipPop.mTip.contains("退款") || mTipPop.mTip.contains("余额不足")) {
                    finish();
                }
            }


        });
        mTipPop.mTvSure.setOnClickListener(v -> PayActivity.start(this, false, false));
        mBinding.tvGetCode.setOnClickListener(v -> {
            if (mTimerUtils == null) {
                mTimerUtils = new Timer2Utils(mBinding.tvGetCode, 60000, 1000);
            }
            mTimerUtils.start();
            mModel.applyAuditSendCode(this, mBeanList.get(mInvoicePop.mIndex).id);

        });
        mBinding.tvSure.setOnClickListener(v -> {
            if (mSel) {
                if (Utils.isEmpty(mBinding.tvSelect.getText().toString())) {
                    mTipPop.initStr("暂无退款验证人，请前往PC端配置", null, "知道了");
                    mTipPop.show();
                    return;
                }
                if (Utils.isEmpty(mBinding.etCode.getText().toString())) {
                    MToast.showToast(Utils.getContext(), "请输入验证码");
                    return;
                }
            } else {
                if (Utils.isEmpty(mBinding.etContent.getText().toString())) {
                    MToast.showToast(Utils.getContext(), "请填写备注信息");
                    return;
                }
            }
            Map map = new HashMap();
            map.put("auditResult", mSel);
            map.put("code", mBinding.etCode.getText().toString());
            map.put("remark", mBinding.etContent.getText().toString());
            map.put("orderId", mData.orderId);
            map.put("reviewerId", mBeanList.get(mInvoicePop.mIndex).id);
            mModel.applyAudit(this, map);
        });
        mBinding.tvCancel.setOnClickListener(v -> finish());
        mBinding.llSelect.setOnClickListener(v ->
                {
                    if (Utils.isEmpty(mBinding.tvSelect.getText().toString())) {
                        mTipPop.initStr("暂无退款验证人，请前往PC端配置", null, "知道了");
                        mTipPop.show();
                    } else {
                        mInvoicePop.show(mInvoicePop.mIndex, "选择退款验证人", mBinding.view, mStringList);
                    }
                }
        );
        mBinding.llNoBtn.setOnClickListener(v -> {
            if (!mSel) return;
            mSel = false;
            mBinding.llNo.setVisibility(View.GONE);
            mBinding.tvShow.setVisibility(View.VISIBLE);
            mBinding.ivNo.setImageResource(R.mipmap.yigouxuan);
            mBinding.ivYes.setImageResource(R.mipmap.weigouxuan);
            mBinding.etContent.setText("");
        });
        mBinding.llYesBtn.setOnClickListener(v -> {
            if (mSel) return;
            mSel = true;
            mBinding.etCode.setText("");
            mBinding.tvGetCode.setText("获取验证码");
            mBinding.etContent.setText("");
            mBinding.tvGetCode.setTextColor(Utils.getColor(R.color.color_B79255));
            if (mStringList != null && mStringList.size() != 0) {
                mBinding.tvSelect.setText(mStringList.get(0));
                mBinding.tvSelect.setTextColor(Utils.getColor(R.color.color_000000));
            } else {
                mBinding.tvSelect.setText("");
                mBinding.tvSelect.setTextColor(Utils.getColor(R.color.color_C0C4CC));
            }
            mBinding.llNo.setVisibility(View.VISIBLE);
            mBinding.tvShow.setVisibility(View.GONE);
            mBinding.ivNo.setImageResource(R.mipmap.weigouxuan);
            mBinding.ivYes.setImageResource(R.mipmap.yigouxuan);
        });
        mBinding.ivBack.setOnClickListener(v -> finish());
    }

    @Override
    public void initObserve() {
        mBinding.etContent.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Utils.hide(this);
            }
        });
        mModel.mErrorCode.observe(this, s -> {
            if (Utils.isEmpty(s)) {
                mTipPop.initStr(mSel ? "同意退款，提交成功！" : "拒绝退款，提交成功！", null, "知道了");
                mTipPop.show();
                return;
            }
            if (s.equals("E00462619")) {
                mTipPop.initStr("可退金额不足", null, "知道了");
            } else if (s.equals("E00462632")) {
                mTipPop.initStr("抱歉，当前您的账户余额不足，请充值后再操作！", "去充值", "知道了");
            } else if (s.equals("E80810020")) {
                mTipPop.initStr("退款申请不存在，请刷新重试", null, "知道了");
            } else if (s.equals("E80810004")) {
                mTipPop.initStr("退款状态已发生变化，请刷新后再进行操作。", null, "知道了");
            } else if (s.equals("E80810017")) {
                mTipPop.initStr("验证码不存在，请获取验证码", null, "知道了");
            } else if (s.equals("E80810018")) {
                mTipPop.initStr("验证码错误", null, "知道了");
            } else if (s.equals("E80810022")) {
                mTipPop.initStr("暂不支持处理超期退款，请前往PC端处理！", null, "知道了");
            }
            mTipPop.show();
        });
        mModel.mListBean.observe(this, listBeans -> {
            if (listBeans == null || listBeans.size() == 0) {
                return;
            }
            mStringList = new ArrayList<>();
            mBeanList = listBeans;
            for (ListBean bean : listBeans) {
                String phone = bean.reviewerPhone;
                mStringList.add(bean.reviewerName + " (" + phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4) + ")");
            }
            mBinding.tvSelect.setText(mStringList.get(0));
            mBinding.tvSelect.setTextColor(Utils.getColor(R.color.color_000000));
            mInvoicePop.mList = mStringList;
        });
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_SELECT:
                String index = (String) event.data;
                mBinding.tvSelect.setText(index);
                mBinding.tvSelect.setTextColor(Utils.getColor(R.color.color_000000));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}